package com.laolei.core.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.laolei.core.Context;
import com.laolei.core.logging.RunTimeLog;

/**
 * 记录收到的http请求.
 * 
 * @author Administrator
 *
 */
@Component
@ComponentScan
public class LoggerInterceptor extends HandlerInterceptorAdapter {
	private final static Logger logger = LoggerFactory.getLogger(LoggerInterceptor.class);

	@Override
	public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
		Context.init(request, response);
		String url = Context.getRequestUri();
		boolean state = true;
		if (filterLogger(url)) {
			logger.debug("已接受到请求:{}", url);
			Context.sendUserId();
			state = true;
		} else {
			logger.info("资源{}不允许访问!", url);
			state = false;
		}
		return state;
	}

	private boolean filterLogger(final String url) {
		return (url.isEmpty() || url.indexOf('.') == -1 || url.endsWith(".do") || url.endsWith(".json"));
	}

	@Override
	public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) throws Exception {
		String url = request.getRequestURI();
		if (!filterLogger(url))
			return;
		long runtime = (System.currentTimeMillis() - Context.getBeginTime());
		RunTimeLog.log(runtime, "请求已结束:{}", url);
		if (ex != null)
			logger.error("请求{}出错 : {}", url, ex.getMessage());
		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
		response.addHeader("Access-Control-Allow-Headers", "Content-Type");
		Context.remove();
	}
}